const express = require('express')
const uploadRouter = express.Router();
const upload = require("../model/qiniu.js")

const multer = require("multer");
let uploadResult = multer({ dest: "./public/uploadImage" });
const fs = require("fs");

uploadRouter.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    next();
});

uploadRouter.post('/formData', uploadResult.single('avatar'), async(req, res) => {
    let publicPath = req.file.path;
    let picName = req.file.filename;
    let uploadStatus = await upload(picName, publicPath);
    fs.unlink(publicPath, function(err) {
        if (err) {
            throw err;
        }
    })
    res.send(uploadStatus)
})

uploadRouter.post("/", uploadResult.single('avatar'), async(req, res) => {
    let publicPath = req.file.path;
    let picName = req.file.filename;
    let uploadStatus = await upload(picName, publicPath);
    fs.unlink(publicPath, function(err) {
        if (err) {
            throw err;
        }
    })
    res.setHeader('Content-Type', 'text/html');
    res.send(uploadStatus)
})

module.exports = uploadRouter;